package first.endtoend

import first.endtoend.messages.MessageCode
import org.springframework.dao.DataIntegrityViolationException
import org.springframework.web.multipart.MultipartFile
import org.springframework.web.multipart.MultipartHttpServletRequest

class BeneficiaryController
{

    // static allowedMethods = [save: "POST", update: "POST", delete: "POST"]

    def scaffold = true
    Agent agentInstance
    def pathImage = ""

    def index()
    {
        redirect(action: "list", controller: "family")

    }

    def list(Integer max)
    {
        redirect(action: "list", controller: "family")
        /*params.max = Math.min(max ?: 10, 100)
        [beneficiaryInstanceList: Beneficiary.list(params), beneficiaryInstanceTotal: Beneficiary.count()]
*/
    }

    def create(Long id)
    {

        println(params)
        [beneficiaryInstance: new Beneficiary(params), familyInstance: Family.get(id)]
    }

    /*
    @author: Olfa
     */

    def upload()
    {
        def results = []
        if (request instanceof MultipartHttpServletRequest)
        {
            for (filename in request.getFileNames())
            {
                MultipartFile file = request.getFile(filename)

                String newFileName = UUID.randomUUID().toString() + file.originalFilename.substring(file.originalFilename.lastIndexOf("."))
                println(file.originalFilename.substring(file.originalFilename.lastIndexOf(".")))
                // file.transferTo(new File("${grailsApplication.config.file.upload.directory?:'/tmp'}/tmp/$newFileName"))
                def photo = grailsApplication.config.benefPhoto + $newFileName
                file.transferTo(new File("web-app/benefPhotos/$newFileName"))
                pathImage = "$newFileName"
                session["pathImg"] = pathImage

                results << [
                        name         : file.originalFilename,
                        size         : file.size,
                        url          : createLink(controller: 'image', action: 'image'),
                        thumbnail_url: createLink(controller: 'image', action: 'image'),
                        delete_url   : createLink(controller: 'image', action: 'image'),
                        delete_type  : "DELETE"
                ]
            }
        }

    }

    def save()
    {
        println("executing save Beneficiary!" + params)
        def beneficiaryInstance = new Beneficiary(params)
        beneficiaryInstance.save(flush: true)
        println("benef = " + beneficiaryInstance.toString())
        println("HERE ***" + params.family.id)
        def familyInstance = Family.findById(Long.valueOf(params.family.id))
        if (!familyInstance)
        {
            println("NO FAMILY FOUND")
        } else
        {
            if (familyInstance.beneficiaries.size() > 0)
            {
                println("there is beneficiaries for this family")
                familyInstance.beneficiaries.add(beneficiaryInstance)
                familyInstance.save(flush: true)
            } else
            {
                familyInstance.beneficiaries = new ArrayList<Beneficiary>()
                familyInstance.beneficiaries.add(beneficiaryInstance)
                familyInstance.save()
            }
        }
        if (!beneficiaryInstance.save(flush: true))
        {
            redirect(action: "create", controllerName: "Beneficiary", id: familyInstance.id)
            [beneficiaryInstance: beneficiaryInstance, familyInstance: familyInstance]
            return
        }

        //here add a notification to DB
        FairPricesShop fpsInstance = familyInstance.fps
        if (fpsInstance)
        {
            agentInstance = Agent.findByFps(fpsInstance)
        }

        Notification notificationInstance
        if (agentInstance && familyInstance.rationCard != null)
        {
            notificationInstance = new Notification(agent: agentInstance, idModel: familyInstance.id, code: MessageCode.FAMILY_UPDATE.value(), modelName: Family.getSimpleName(), description: message(code: 'beneficiary.add.notification.message' + beneficiaryInstance.firstName, default: "Add benef")).save()
        } else
        {

        }
        flash.message = message(code: 'default.created.message', args: [message(code: 'beneficiary.label', default: 'Beneficiary'), beneficiaryInstance.id])
        redirect(controller: "family", action: "show", id: beneficiaryInstance.familyId)
    }

    def show(Long id)
    {
        def beneficiaryInstance = Beneficiary.get(id)
        if (!beneficiaryInstance)
        {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'beneficiary.label', default: 'Beneficiary'), id])
            redirect(action: "list")
            return
        }

        [beneficiaryInstance: beneficiaryInstance]
    }

    def edit(Long id)
    {
        def beneficiaryInstance = Beneficiary.get(id)
        if (!beneficiaryInstance)
        {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'beneficiary.label', default: 'Beneficiary'), id])
            redirect(action: "list")
            return
        }

        [beneficiaryInstance: beneficiaryInstance]
    }

    def update(Long id, Long version)
    {
        def beneficiaryInstance = Beneficiary.get(id)
        if (!beneficiaryInstance)
        {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'beneficiary.label', default: 'Beneficiary'), id])
            redirect(action: "list")
            return
        }

        if (version != null)
        {
            if (beneficiaryInstance.version > version)
            {
                beneficiaryInstance.errors.rejectValue("version", "default.optimistic.locking.failure",
                        [message(code: 'beneficiary.label', default: 'Beneficiary')] as Object[],
                        "Another user has updated this Beneficiary while you were editing")
                render(view: "edit", model: [beneficiaryInstance: beneficiaryInstance])
                return
            }
        }

        beneficiaryInstance.properties = params

        if (!beneficiaryInstance.save(flush: true))
        {
            render(view: "edit", model: [beneficiaryInstance: beneficiaryInstance])
            return
        }

        Family familyInstance = beneficiaryInstance.family
        FairPricesShop fpsInstance
        if (familyInstance)
        {
            fpsInstance = familyInstance.fps
        } else
        {
        }
        if (fpsInstance)
        {
            agentInstance = Agent.findByFps(fpsInstance)

        }

        Notification notificationInstance
        if (agentInstance && familyInstance.rationCard != null)
        {
            notificationInstance = new Notification(agent: agentInstance, idModel: familyInstance.id, code: MessageCode.FAMILY_UPDATE.value(), modelName: Family.getSimpleName(), description: message(code: 'beneficiary.update.notification.message' + beneficiaryInstance.firstName, default: "update benef")).save()
        } else
        {

        }



        flash.message = message(code: 'default.updated.message', args: [message(code: 'beneficiary.label', default: 'Beneficiary'), beneficiaryInstance.id])
        //redirect(action: "show", id: beneficiaryInstance.id)
        redirect(controller: "family", action: "show", id: beneficiaryInstance.familyId)
    }


    def delete(Long id)
    {
        def beneficiaryInstance = Beneficiary.get(id)
        if (!beneficiaryInstance)
        {
            flash.message = message(code: 'default.not.found.message', args: [message(code: 'beneficiary.label', default: 'Beneficiary'), id])
            redirect(action: "list")
            return
        }
        Family familyInstance = beneficiaryInstance.family
        FairPricesShop fpsInstance

        try
        {
            beneficiaryInstance.delete(flush: true)
            if (familyInstance)
            {
                fpsInstance = familyInstance.fps
            } else
            {
            }
            if (fpsInstance)
            {
                agentInstance = Agent.findByFps(fpsInstance)

            }

            Notification notificationInstance
            if (agentInstance && familyInstance.rationCard != null)
            {
                notificationInstance = new Notification(agent: agentInstance, idModel: beneficiaryInstance.id, code: MessageCode.BENEF_DELETE.value(), modelName: Family.getSimpleName(), description: message(code: 'beneficiary.delete.notification.message' + beneficiaryInstance.firstName, default: "delete benef")).save()
            } else
            {

            }


            flash.message = message(code: 'default.deleted.message', args: [message(code: 'beneficiary.label', default: 'Beneficiary'), id])
            //redirect(action: "list")
            redirect(controller: "family", action: "show", id: beneficiaryInstance.familyId)
        }
        catch (DataIntegrityViolationException e)
        {
            flash.message = message(code: 'default.not.deleted.message', args: [message(code: 'beneficiary.label', default: 'Beneficiary'), id])
            redirect(action: "show", id: id)
        }
    }


}
